<!--
 * @Description: api测试
 * @Author: ZhangHan
 * @Date: 2025-08-15 16:31:49
 * @LastEditTime: 2025-08-20 10:42:50
 * @LastEditors: ZhangHan
-->
<template>
  <view>
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="title">uni-app 微信小程序测试</view>
      <view class="subtitle">基于uni API的微信小程序能力测试</view>
    </view>
    <!-- 标签导航 -->
    <scroll-view class="tabs-scroll" scroll-x>
      <view class="tabs">
        <view
          v-for="(tab, index) in tabs"
          :key="index"
          class="tab-item"
          :class="{ active: activeTab === index }"
          @click="activeTab = index"
        >
          {{ tab }}
        </view>
      </view>
    </scroll-view>
    <!-- 内容区域 -->
    <scroll-view class="content" scroll-y>
      <!-- 基础能力 -->
      <view v-if="activeTab === 0" class="api-group">
        <view class="group-title">基础能力</view>

        <view class="api-card">
          <view class="api-title">获取系统信息</view>
          <view class="api-desc"
            >使用 uni.getSystemInfo 获取设备和微信版本信息</view
          >
          <button class="api-btn" @click="getSystemInfo">获取信息</button>
          <view class="result-box" v-if="systemInfo && systemInfo != '{}'">
            <view class="result-content">{{ formatJson(systemInfo) }}</view>
          </view>
        </view>

        <view class="api-card">
          <view class="api-title">获取授权设置</view>
          <view class="api-desc">使用 uni.getSetting 获取用户授权状态</view>
          <button class="api-btn" @click="getSetting">获取设置</button>
          <view class="result-box" v-if="settingInfo && settingInfo != '{}'">
            <view class="result-content">{{ formatJson(settingInfo) }}</view>
          </view>
        </view>

        <view class="api-card">
          <view class="api-title">打开授权设置</view>
          <view class="api-desc">使用 uni.openSetting 打开设置界面</view>
          <button class="api-btn secondary" @click="openSetting">
            打开设置
          </button>
        </view>
      </view>
      <!-- 用户能力 -->
      <view v-if="activeTab === 1" class="api-group">
        <view class="group-title">用户能力</view>

        <view class="api-card">
          <view class="api-title">获取用户信息</view>
          <view class="api-desc"
            >使用 uni.getUserProfile 获取用户信息（微信特有）</view
          >
          <button class="api-btn" @click="getUserProfile">获取用户信息</button>
          <view class="result-box" v-if="userProfile">
            <view class="user-info">
              <image :src="userProfile.avatarUrl" class="avatar"></image>
              <view class="user-name">{{ userProfile.nickName }}</view>
              <view class="user-gender"
                >性别:
                {{
                  userProfile.gender === 1
                    ? "男"
                    : userProfile.gender === 2
                    ? "女"
                    : "未知"
                }}</view
              >
            </view>
            <view class="result-content">{{ formatJson(userProfile) }}</view>
          </view>
        </view>

        <view class="api-card">
          <view class="api-title">获取用户手机号</view>
          <view class="api-desc">使用 button open-type="getPhoneNumber"</view>
          <button
            class="api-btn danger"
            open-type="getPhoneNumber"
            @getphonenumber="getPhoneNumber"
          >
            获取手机号
          </button>
          <view class="result-box" v-if="phoneNumberResult">
            <view class="result-content">{{ phoneNumberResult }}</view>
          </view>
        </view>

        <view class="api-card">
          <view class="api-title">用户登录</view>
          <view class="api-desc">使用 uni.login 获取登录凭证</view>
          <button class="api-btn" @click="userLogin">用户登录</button>
          <view class="result-box" v-if="loginCode">
            <view class="result-title">登录凭证 code (服务端使用):</view>
            <view class="result-content">{{ loginCode }}</view>
          </view>
        </view>
      </view>

      <!-- 社交分享 -->
      <view v-if="activeTab === 2" class="api-group">
        <view class="group-title">社交分享</view>

        <view class="api-card">
          <view class="api-title">分享给好友</view>
          <view class="api-desc"
            >使用 uni.share 或 button open-type="share"</view
          >
          <button class="api-btn" open-type="share">分享</button>
          <!-- #ifdef APP-PLUS -->
          <button class="api-btn secondary" @click="shareWithUniAPI">
            使用uni.share
          </button>
          <!-- #endif  -->
          <view class="result-box" v-if="shareResult">
            <view class="result-content">{{ shareResult }}</view>
          </view>
        </view>

        <view class="api-card">
          <view class="api-title">联系客服</view>
          <view class="api-desc">使用 button open-type="contact"</view>
          <button class="api-btn" open-type="contact">联系客服</button>
        </view>
      </view>
    </scroll-view>
    <!-- 底部信息 -->
    <view class="footer">
      <view class="footer-text">uni-app 微信小程序测试工具</view>
      <view class="footer-text">使用 uni API 开发，兼容微信小程序</view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";

// 类型定义
interface UserProfile {
  nickName: string;
  avatarUrl: string;
  gender: number;
  province: string;
  city: string;
  country: string;
  [key: string]: any;
}

// 标签数据
const tabs = ["基础能力", "用户能力", "社交分享", "微信特有能力"];

const activeTab = ref(0);
const isLoading = ref(false);

// 基础能力
const systemInfo = ref<any | null>(null);
const settingInfo = ref<any | null>(null);

// 用户能力
const userProfile = ref<UserProfile | null | any>(null);
const phoneNumberResult = ref<string | null>(null);
const loginCode = ref<string | null>(null);

// 社交分享
const shareResult = ref<string | null>(null);

// 微信特有能力
const payAmount = ref<number>(0.01);
const paymentResult = ref<string | null>(null);
const subscribeResult = ref<any | null>(null);
const biometricSupported = ref(false);
const biometricResult = ref<string | null>(null);

// 格式化JSON--易读版本
const formatJson = (json: any): string => {
  return JSON.stringify(json, null, 2);
};

// 基础能力方法
const getSystemInfo = async () => {
  try {
    isLoading.value = true;
    const res = await uni.getSystemInfo();
    systemInfo.value = res;
  } catch (err) {
    systemInfo.value = `获取失败: ${JSON.stringify(err)}`;
  } finally {
    isLoading.value = false;
  }
};

const getSetting = async () => {
  try {
    isLoading.value = true;
    const res = await uni.getSetting();
    settingInfo.value = res.authSetting;
  } catch (err) {
    settingInfo.value = `获取失败: ${JSON.stringify(err)}`;
  } finally {
    isLoading.value = false;
  }
};

const openSetting = async () => {
  try {
    isLoading.value = true;
    const res = await uni.openSetting();
    settingInfo.value = res.authSetting;
    uni.showToast({
      title: "设置已更新",
      icon: "success",
    });
  } catch (err) {
    uni.showToast({
      title: "操作失败",
      icon: "none",
    });
  } finally {
    isLoading.value = false;
  }
};

// 用户能力方法
const getUserProfile = async () => {
  try {
    isLoading.value = true;
    // @ts-ignore: 微信特有API，uni-app兼容
    const res = await uni.getUserProfile({
      desc: "用于完善用户资料",
    });
    userProfile.value = res.userInfo;
  } catch (err: any) {
    userProfile.value = null;
    uni.showToast({
      title: err.errMsg || "获取失败",
      icon: "none",
    });
  } finally {
    isLoading.value = false;
  }
};

const getPhoneNumber = (e: any) => {
  if (e.detail.errMsg === "getPhoneNumber:ok") {
    // 实际开发中，需要将code发送到后端解密
    phoneNumberResult.value = `获取加密手机号成功，code: ${e.detail.code}\n请将此code发送到服务器解密`;
  } else {
    phoneNumberResult.value = `获取失败: ${e.detail.errMsg}`;
  }
};

const userLogin = async () => {
  try {
    isLoading.value = true;
    const res = await uni.login();
    if (res.code) {
      loginCode.value = res.code;
    } else {
      loginCode.value = `登录失败: ${res.errMsg}`;
    }
  } catch (err: any) {
    loginCode.value = `登录失败: ${err.message}`;
  } finally {
    isLoading.value = false;
  }
};

// 社交分享方法
const shareWithUniAPI = async () => {
  try {
    isLoading.value = true;
    const res = await uni.share({
      title: "uni-app微信小程序测试",
      path: "/packageB/testApi/index",
      imageUrl: "",
      success: () => {
        shareResult.value = "分享成功";
        setTimeout(() => (shareResult.value = null), 2000);
      },
      fail: (err: any) => {
        console.log(err);

        shareResult.value = `分享失败: ${err.errMsg}`;
        setTimeout(() => (shareResult.value = null), 2000);
      },
    });
  } catch (err: any) {
    console.log(err, "---------");
    shareResult.value = `分享失败: ${err.message}`;
    setTimeout(() => (shareResult.value = null), 2000);
  } finally {
    isLoading.value = false;
  }
};

onShareAppMessage(() => {
  return {
    title: "testApi",
    path: "/packageB/testApi/index",
  };
});

// 没掏钱 不行 必须掏钱一年30 认证过后才行
onShareTimeline(() => {
  return {
    title: "testApi",
    path: "/packageB/testApi/index",
  };
});
</script>

<style lang="scss" scoped>
$primary-color: #07c160; // 微信绿色
$primary-dark: #06ae56;
$secondary-color: #1677ff;
$danger-color: #ff4d4f;
$text-primary: #333;
$text-secondary: #666;
$text-tertiary: #999;
$background: #f5f7fa;
$card-bg: #ffffff;
$border-color: #eee;
$radius: 16rpx;
$small-radius: 8rpx;

.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: $background;
}

.header {
  padding: 30rpx 20rpx;
  background-color: $primary-color;
  color: white;
  text-align: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

  .title {
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 10rpx;
  }

  .subtitle {
    font-size: 24rpx;
    opacity: 0.9;
  }
}

.tabs-scroll {
  width: 100%;
  background-color: $card-bg;
  border-bottom: 1px solid $border-color;
}

.tabs {
  display: flex;
  flex-direction: row;
  padding: 0 10rpx;
}

.tab-item {
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: $text-secondary;
  position: relative;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.3s;

  &.active {
    color: $primary-color;
    font-weight: bold;

    &::after {
      content: "";
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 4rpx;
      background-color: $primary-color;
    }
  }
}

.content {
  flex: 1;
  padding: 20rpx;
  box-sizing: border-box;
}

.api-group {
  margin-bottom: 30rpx;

  .group-title {
    font-size: 30rpx;
    font-weight: bold;
    color: $primary-color;
    margin: 20rpx 0;
    padding-left: 10rpx;
    border-left: 6rpx solid $primary-color;
  }
}

.api-card {
  background-color: $card-bg;
  border-radius: $radius;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);

  .api-title {
    font-size: 30rpx;
    font-weight: bold;
    color: $text-primary;
    margin-bottom: 10rpx;
  }

  .api-desc {
    font-size: 24rpx;
    color: $text-secondary;
    margin-bottom: 20rpx;
    line-height: 1.5;
  }

  .api-btn {
    background-color: $primary-color;
    color: white;
    border-radius: $small-radius;
    padding: 15rpx 0;
    font-size: 26rpx;
    width: 100%;
    margin-bottom: 20rpx;
    transition: background-color 0.3s;

    &.secondary {
      background-color: $secondary-color;
    }

    &.danger {
      background-color: $danger-color;
    }

    &:hover {
      opacity: 0.9;
    }

    &:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }
  }

  .result-box {
    background-color: #f8f9fa;
    border-radius: $small-radius;
    padding: 20rpx;
    font-size: 24rpx;
    overflow-x: auto;
    border-left: 4rpx solid $primary-color;

    .result-title {
      font-weight: bold;
      color: $text-primary;
      margin-bottom: 10rpx;
      font-size: 26rpx;
    }

    .result-content {
      color: $text-secondary;
      white-space: pre-wrap;
      word-wrap: break-word;
      line-height: 1.6;
    }
  }

  .api-input {
    border: 1px solid #ddd;
    border-radius: $small-radius;
    padding: 15rpx;
    font-size: 26rpx;
    margin-bottom: 20rpx;
    width: 100%;
    box-sizing: border-box;
  }

  .pay-amount {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    font-size: 26rpx;

    .amount-input {
      flex: 1;
      margin: 0 16rpx;
      padding: 16rpx;
      border: 1px solid $border-color;
      border-radius: $small-radius;
      font-size: 26rpx;
    }
  }

  .user-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20rpx;

    .avatar {
      width: 120rpx;
      height: 120rpx;
      border-radius: 50%;
      margin-bottom: 10rpx;
    }

    .user-name {
      font-size: 28rpx;
      font-weight: bold;
      margin-bottom: 5rpx;
    }

    .user-gender {
      font-size: 24rpx;
      color: $text-secondary;
      margin-bottom: 15rpx;
    }
  }
}

.footer {
  background-color: $card-bg;
  padding: 20rpx;
  text-align: center;
  border-top: 1px solid $border-color;

  .footer-text {
    font-size: 22rpx;
    color: $text-tertiary;
    margin: 5rpx 0;
  }
}

// 加载组件样式
::v-deep .uni-loading-page {
  z-index: 9999;
}
</style>
